# -*- coding: utf-8 -*-
"""
认证相关路由
@api-version: 1.0.0
REF: API-AUTH-001~003
"""

from flask import Blueprint, request, g
from marshmallow import ValidationError
from backend.models.user import User
from backend.models.session import UserSession
from backend.schemas.user_schemas import LoginSchema
from backend.utils.response import success_response, error_response, validation_error_response
from backend.utils.auth import token_required, get_client_ip, get_user_agent
from backend.models import db

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/auth/login', methods=['POST'])
def login():
    """用户登录接口
    REF: API-AUTH-001
    """
    try:
        # 数据验证
        schema = LoginSchema()
        data = schema.load(request.get_json() or {})
        
        email = data['email']
        password = data['password']
        
        # 查找用户
        user = User.query.filter_by(email=email).first()
        if not user:
            return error_response('邮箱或密码错误', 401)
        
        # 验证密码
        if not user.check_password(password):
            return error_response('邮箱或密码错误', 401)
        
        # 检查用户状态
        if not user.is_active():
            return error_response('账户已被禁用', 403)
        
        # 清理该用户的过期会话
        from datetime import datetime
        from backend.utils.datetime_utils import get_local_now
        UserSession.query.filter(
            UserSession.user_id == user.id,
            UserSession.expires_at < datetime.utcnow()
        ).delete()
        
        # 更新最后登录时间（使用本地时间）
        user.last_login = get_local_now()
        
        # 创建新会话
        session = UserSession(
            user_id=user.id,
            ip_address=get_client_ip(),
            user_agent=get_user_agent()
        )
        
        db.session.add(session)
        db.session.commit()
        
        # 返回登录成功响应
        response_data = {
            'access_token': session.token,
            'refresh_token': session.refresh_token,
            'expiresAt': session.expires_at.isoformat(),
            'user': user.to_dict()
        }
        
        return success_response(response_data, '登录成功')
        
    except ValidationError as e:
        return validation_error_response(e.messages)
    except Exception as e:
        # 记录详细错误信息
        import traceback
        error_msg = f"登录失败: {str(e)}"
        print(f"❌ {error_msg}")
        print(f"详细错误: {traceback.format_exc()}")
        return error_response(error_msg, 500)

@auth_bp.route('/auth/logout', methods=['POST'])
@token_required
def logout():
    """用户登出接口
    REF: API-AUTH-002
    """
    try:
        # 删除当前会话
        db.session.delete(g.current_session)
        db.session.commit()
        
        return success_response(message='登出成功')
        
    except Exception as e:
        return error_response('登出失败', 500)

@auth_bp.route('/auth/refresh', methods=['POST'])
def refresh_token():
    """刷新Token接口
    REF: API-AUTH-003
    """
    try:
        data = request.get_json() or {}
        refresh_token = data.get('refresh_token')
        
        if not refresh_token:
            return error_response('缺少refresh_token', 400)
        
        # 查找会话
        session = UserSession.query.filter_by(refresh_token=refresh_token).first()
        if not session:
            return error_response('refresh_token无效', 401)
        
        if session.is_expired():
            # 删除过期会话
            db.session.delete(session)
            db.session.commit()
            return error_response('refresh_token已过期', 401)
        
        # 获取用户信息
        user = User.query.get(session.user_id)
        if not user or not user.is_active():
            return error_response('用户不存在或已被禁用', 401)
        
        # 刷新会话
        session.refresh()
        session.ip_address = get_client_ip()
        session.user_agent = get_user_agent()
        
        db.session.commit()
        
        # 返回新的Token
        response_data = {
            'access_token': session.token,
            'refresh_token': session.refresh_token,
            'expiresAt': session.expires_at.isoformat(),
            'user': user.to_dict()
        }
        
        return success_response(response_data, 'Token刷新成功')
        
    except Exception as e:
        return error_response('Token刷新失败', 500)

@auth_bp.route('/auth/verify', methods=['GET'])
@token_required
def verify_token():
    """验证Token有效性
    REF: API-AUTH-004
    """
    try:
        return success_response({
            'user': g.current_user.to_dict(),
            'session': {
                'expiresAt': g.current_session.expires_at.isoformat(),
                'ipAddress': g.current_session.ip_address
            }
        }, 'Token有效')
        
    except Exception as e:
        return error_response('Token验证失败', 500)